package com.rock.drawboard.thread;

import com.rock.drawboard.constant.EventConfig;
import com.rock.drawboard.event.BoardEvent;
import com.rock.drawboard.event.LoginEvent;
import com.rock.drawboard.module.DataPackage;
import com.rock.drawboard.utils.LogUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务端 - 接收 - 数据
 */
public class ServerReceiveThread extends Thread {
    public ServerSocket serverSocket = null;
    static Socket socket;
    ObjectInputStream input;

    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(30000);
            socket = serverSocket.accept();
            input = new ObjectInputStream(socket.getInputStream());
            LogUtils.e("LoginActivity2-ServerReceiveThread", "receive - accept");

            input();

        } catch (IOException e1) {
            e1.printStackTrace();
            LogUtils.e("LoginActivity2-ServerReceiveThread", "IOException e1");
        }
    }

    private void input() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        DataPackage dtpg = (DataPackage) input.readObject();
                        Object data = dtpg.getData();
                        LogUtils.e("LoginActivity2-ServerReceiveThread", dtpg.getType() + "");
                        switch (dtpg.getType()) {
                            case POINT:
                                EventBus.getDefault().post(new BoardEvent(EventConfig.POINT, data));
                                break;
                            case COMMAND:
                                EventBus.getDefault().post(new BoardEvent(EventConfig.COMMAND, data));
                                break;
                            case COLOR:
                                EventBus.getDefault().post(new BoardEvent(EventConfig.COLOR, data));
                                break;
                            case BG_COLOR:
                                EventBus.getDefault().post(new BoardEvent(EventConfig.BG_COLOR, data));
                                break;
                            case STROKE:
                                EventBus.getDefault().post(new BoardEvent(EventConfig.STROKE, data));
                                break;
                        }

                    } catch (IOException e2) {
                        LogUtils.e("LoginActivity2- ServerReceiveThread", "IOException e2");
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                        LogUtils.e("LoginActivity2- ServerReceiveThread", "ClassNotFoundException");
                    }
                }

            }
        }).start();
    }

}
